package com.freemalll.merchant.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freemalll.common.core.exception.BusinessException;
import com.freemalll.merchant.common.CommonEnum;
import com.freemalll.merchant.domain.dto.BusinessLicenseDto;
import com.freemalll.merchant.domain.dto.merchantParameters.MerParamsDetailDTO;
import com.freemalll.merchant.domain.entity.MerLicense;
import com.freemalll.merchant.service.MerLicenseService;
import com.freemalll.merchant.service.MerMerchantService;
import com.freemalll.merchant.service.MerParamsService;
import com.freemalll.merchant.mapper.MerLicenseMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 服务层实现。
 *
 * @author songshixiong
 * @since 2025-05-14
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MerLicenseServiceImpl extends ServiceImpl<MerLicenseMapper, MerLicense> implements MerLicenseService {

    @Resource
    private MerParamsService merParamsService;
    @Resource
    private MerMerchantService merMerchantService;

    @Override
    public BusinessLicenseDto getBusinessLicenseById(String merId) {
        return baseMapper.getBusinessLicenseById(merId);
    }

    @Override
    public void checkMerchant(String licenseCode, String licenseName, String licenseShortName, boolean checkMerShortName, String merId) {
        //默认90天
        int limitTheNumberOfDays = 90;
        // 提交初审的时候，如果申请的商户在90之内存在有拒绝的商户入驻申请，那就在提交初审页面上传营业执照时提示（该商户近90天内存在审批拒绝的申请） 然后不允许上传那个商户的营业执照
        List<MerParamsDetailDTO> examineRefuse = merParamsService.getParams("examine_refuse", null);
        if (CollectionUtils.isNotEmpty(examineRefuse)) {
            limitTheNumberOfDays = Integer.parseInt(examineRefuse.get(0).getParamKey());
        }
        List<String> authStatus = Arrays.asList(CommonEnum.auditType.REVIEW_REFUSED.name(), CommonEnum.auditType.INITIAL_REVIEW_REFUSED.name());
        if (StringUtils.hasText(licenseName)) {
            boolean merchantNameFlag = merMerchantService.checkMerNameAndLimitDay(limitTheNumberOfDays, licenseName, authStatus, merId);
            if (merchantNameFlag) {
                throw BusinessException.businessParamsNotExist("已存在相同商户名称的商户入驻申请");
            }
        }
        if (StringUtils.hasText(licenseCode)) {
            //获取在限制天数内是否存在有拒绝的商户
            boolean flag = merMerchantService.checkIfThereIsAMerchantPresent(limitTheNumberOfDays, licenseCode, authStatus, merId);
            if (flag) {
                throw BusinessException.businessParamsNotExist("已存在相同信用代码的商户入驻申请");
            }
        }
        if (StringUtils.hasText(licenseShortName) && checkMerShortName) {
            boolean merShortNameFlag = merMerchantService.checkMerShortNameAndLimitDay(limitTheNumberOfDays, licenseShortName, authStatus, merId);
            if (merShortNameFlag) {
                throw BusinessException.businessParamsNotExist("已存在相同商户简称的商户入驻申请");
            }
        }
    }

    @Override
    public void checkLicenseCode(String licenseCode, String licenseName, String licenseShortName, boolean checkMerShortNameFlag, String merId) {
        /**
         * 合作申请新增商户入驻时，提交初审页签中识别营业执照时
         * 1、需要校验当前商户统一信用代码、商户名称、是否与当前正在申请中或申请通过的商户存在相同，
         * 若存在，则报错“已存在相同信用代码/商户名称/商户简称的商户入驻申请”（报错内容根据统一信用代码、商户名称、商户简称自行判断）
         *
         * 非初审/复审拒绝、初审/复审退回、复审通过/取消申请 审核通过
         */
        List<String> authStatus = Arrays.asList(CommonEnum.auditType.SUBMIT_INITIAL_REVIEW.name(),
                CommonEnum.auditType.INITIAL_REVIEW_PASSED.name(),
                CommonEnum.auditType.PENDING_APPROVAL.name(),
                CommonEnum.auditType.APPROVING.name(),
                CommonEnum.auditType.SUPPLEMENTARY_PARTS.name(),
                CommonEnum.auditType.ONLINE.name(),
                CommonEnum.auditType.PENDING_SIGNING.name()
        );
        if (StringUtils.hasText(licenseName)) {
            boolean merchantNameFlag = merMerchantService.checkMerName(licenseName, authStatus, merId);
            if (merchantNameFlag) {
                throw BusinessException.businessParamsNotExist("已存在相同商户名称的商户入驻申请");
            }
        }
        if (StringUtils.hasText(licenseCode)) {
            boolean merchantLicenseCodeFlag = merMerchantService.checkMerchantLicenseCode(licenseCode, authStatus, merId);
            if (merchantLicenseCodeFlag) {
                throw BusinessException.businessParamsNotExist("已存在相同信用代码的商户入驻申请");
            }
        }
        if (StringUtils.hasText(licenseShortName) && checkMerShortNameFlag) {
            boolean merShortNameFlag = merMerchantService.checkMerShortName(licenseShortName, authStatus, merId);
            if (merShortNameFlag) {
                throw BusinessException.businessParamsNotExist("已存在相同商户简称的商户入驻申请");
            }
        }
    }

    @Override
    public boolean checkMerchantApplyBtnFlag(String licenseCode, String merId) {
        if (StringUtils.hasText(licenseCode)) {
            //默认90天
            int limitTheNumberOfDays = 90;
            // 提交初审的时候，如果申请的商户在90之内存在有拒绝的商户入驻申请，那就在提交初审页面上传营业执照时提示（该商户近90天内存在审批拒绝的申请） 然后不允许上传那个商户的营业执照
            List<MerParamsDetailDTO> examineRefuse = merParamsService.getParams("examine_refuse", null);
            if (CollectionUtils.isNotEmpty(examineRefuse)) {
                limitTheNumberOfDays = Integer.parseInt(examineRefuse.get(0).getParamKey());
            }
            //获取在限制天数内是否存在有拒绝的商户
            return merMerchantService.checkIfThereIsAMerchantPresent(limitTheNumberOfDays,
                    licenseCode,
                    Arrays.asList(CommonEnum.auditType.REVIEW_REFUSED.name(), CommonEnum.auditType.INITIAL_REVIEW_REFUSED.name()),
                    merId);
        }
        return false;
    }
}
